/*------------------------------------------------------------
 * tcp_send - Send a string to a host machine using TCP
 *------------------------------------------------------------*/

#ifndef NIM_HEADER
#define NIM_HEADER
#include "nim.h";
#endif

#ifndef IOSTREAM
#define IOSTREAM
#include <iostream>
#endif

using namespace std;

int tcp_send(SOCKET s, char *buf, int maxsize, char *host, char *service)
{	// Parameter List:
	// [IN] s      : SOCKET handle
	// [IN] buf    : NULL-terminated string containing bytes to be sent to host
	// [IN] maxsize: Integer containing the maximum number of bytes that buf can hold
	// [IN] host   : NULL-terminated string containing domain name of remote host or IP Address
	//               Broadcast-type IP Address (such as 10.1.255.255) is supported.
	// [IN] service: NULL-terminated String containing service name or port number to use for transmission
	// Return Value: Number of bytes actually sent.
	//NOTE: This function requires winsock2.h header file and ws2_32.lib library file.

	struct hostent  *phe;   /* pointer to host information entry     */
	struct servent	*pse;	/* pointer to service information entry  */
	sockaddr_in		sin;	/* an Intenet endpoint address           */
	long			ihost;	/* 32-bit IP address number              */
	int				len;	/* Number of bytes actually sent         */

	memset(&sin, 0, sizeof(sin));  /* zero the sockaddr_in struct */
	/* Set the address family to AF_INET (= Internet) */
	sin.sin_family = AF_INET;
	/* Map service name (or number) to port number */
	if (pse = getservbyname(service, "TCP"))
		sin.sin_port = pse->s_port;
	else if ( (sin.sin_port = htons( (u_short) atoi(service))) == 0)
	{	cout << "Invalid service request." << endl;
		return INVALID_SOCKET;
	}
	/* Map host name to IP address, allowing for dotted quad */
	ihost = inet_addr(host);
	if (ihost == INADDR_NONE)
	{	phe = gethostbyname(host);
		if (phe)
			memmove(&ihost, phe->h_addr, phe->h_length);
		else
		{	cout << "Invalid host" << endl;
			return INVALID_SOCKET;
		}
	}
	sin.sin_addr.s_addr = ihost;
	buf[maxsize-1] = '\0';
	len = sendto(s,buf,(int)strlen(buf)+1,0,(LPSOCKADDR) &sin, sizeof(sin));
	if (len <= 0)
	{	cout << endl << "Problem with sendto() function call within TCP_send().  Return value = " << len << endl;
	}
	return len;
}